package com.xb.loan.usercenter.user.user.service.impl;

import com.xb.loan.log.exception.BizException;
import com.xb.loan.usercenter.service.user.IUserIdentifyService;
import com.xb.loan.usercenter.service.user.IUserService;
import com.xb.loan.usercenter.service.user.IUserThirdAuthService;
import com.xb.loan.usercenter.service.user.bean.UserIdentifyVO;
import com.xb.loan.usercenter.service.user.bean.UserInfoVO;
import com.xb.loan.usercenter.service.user.bean.UserThirdLoginVO;
import com.xb.loan.usercenter.service.user.constant.UserConst;
import com.xb.loan.usercenter.service.user.exception.IUserServiceException;
import com.xb.loan.usercenter.user.user.dao.UserThirdLoginDao;
import com.xb.loan.usercenter.user.user.dao.bean.UserInfo;
import com.xb.loan.usercenter.user.user.dao.bean.UserThirdLogin;
import com.xb.loan.util.common.ObjectOperation;
import com.xb.loan.util.log.DefaultLoggerFacotry;
import com.xb.loan.util.log.LogFormatTemplate;
import com.xb.loan.util.mybatis.MyTransactional;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 类  描  述 : 用户第三方帐号授权服务接口
 */  
@Service("userThirdAuthService")  
public class UserThirdAuthServiceImpl implements IUserThirdAuthService,IUserServiceException {
    Logger logger = DefaultLoggerFacotry.getLogger(UserThirdAuthServiceImpl.class);
    @Autowired
    UserThirdLoginDao userThirdLoginDao;
    
    @Autowired
    IUserService userService;
    
    @Autowired
    IUserIdentifyService userIdentifyService;
    @Autowired  //①  注入上下文  
    private ApplicationContext context;      
    private UserThirdAuthServiceImpl proxySelf; //②  表示代理对象，不是目标对象
    @PostConstruct  //③ 初始化方法
    private void setSelf() {
        //从上下文获取代理对象（如果通过proxtSelf=this是不对的，this是目标对象）  
        //此种方法不适合于prototype Bean，因为每次getBean返回一个新的Bean  
        proxySelf = (UserThirdAuthServiceImpl) context.getBean(IUserThirdAuthService.class);   
    }

    @Override
    public String registerThirdUser(UserInfoVO userInfoVO, UserThirdLoginVO userThirdLoginVO) throws BizException {
                
        //验证userThirdLoginVO对象必输属性是否存在
        verifyUserThirdLoginVO(userThirdLoginVO);
        
        //判断第三方登录账号已否已存在
        if(queryThirdUser(userThirdLoginVO.getPartnerId(),userThirdLoginVO.getThirdloginType(),userThirdLoginVO.getThirduserId())!=null){            
            
            logger.warn(LogFormatTemplate.USER_THIRD_AUTH_SERVICE_REGISTER_THIRD_USER_WARN, new String[] { "coupon", userThirdLoginVO.getPartnerId(),
                    String.valueOf(userThirdLoginVO.getThirdloginType()), userThirdLoginVO.getThirduserId(), userThirdExist.getMessage() });

            logger.warn(userThirdExist.getMessage(),userThirdExist);
            throw userThirdExist;            
        }
        
             
        String userId = proxySelf.registerThirdUserTransaction(userInfoVO, userThirdLoginVO);
        
        log(LogFormatTemplate.USER_THIRD_AUTH_SERVICE_REGISTER_THIRD_USER,new String[]{"user",userId,userInfoVO.getPartnerId() });
        
        return userId;
    }
    
    private UserInfo queryThirdUser(String partnerId, int thirdLoginType, String thirdUserId){
        Map<String,String> map=new HashMap<String,String>(3);
        map.put("partnerId", partnerId);
        map.put("thirdLoginType", String.valueOf(thirdLoginType));
        map.put("thirdUserId", thirdUserId);       
        //查询第三方帐号类型、账号查询用户信息
        UserInfo userInfo=userThirdLoginDao.login(map);
        return userInfo;
    }
    /**
     * //TODO 添加方法功能描述
     * @param userInfoVO
     * @param userThirdLoginVO
     * @return
     * @throws BizException
     */
    @MyTransactional
    public String registerThirdUserTransaction(UserInfoVO userInfoVO, UserThirdLoginVO userThirdLoginVO) throws BizException  {
        return registerThirdUserCommon(userInfoVO, userThirdLoginVO);
    }

    /**
     * 第三方帐号注册注册公共部分
     * @param userInfoVO
     * @param userThirdLoginVO
     * @return 新注册用户编号
     * @throws BizException
     */
    private String registerThirdUserCommon(UserInfoVO userInfoVO, UserThirdLoginVO userThirdLoginVO) throws BizException {
        //注册用户信息
        String userId = userService.generateUser(userInfoVO,0);
        //注册第三方登录账号信息
        this.registerThirdLogin(userId, userThirdLoginVO);        
 
        return userId;
    }

    /**
     * 验证userThirdLoginVO对象必输属性是否存在
     * @param userThirdLoginVO
     * @throws BizException
     */
    private void verifyUserThirdLoginVO(UserThirdLoginVO userThirdLoginVO) throws BizException {
        if(userThirdLoginVO==null){
            logger.warn(userThirdLoginVoMissing.getMessage(),userThirdLoginVoMissing);
            throw userThirdLoginVoMissing;
        }
        //判断必输值是否都输入
        if(userThirdLoginVO.getThirduserId()==null||"".equals(userThirdLoginVO.getThirduserId())||
            userThirdLoginVO.getPartnerId()==null||"".equals(userThirdLoginVO.getPartnerId())||
            userThirdLoginVO.getThirdloginType()==null
                ){
            logger.warn(userThirdLoginVoFieldMissing.getMessage(),userThirdLoginVoFieldMissing);
            throw userThirdLoginVoFieldMissing;
        }
    }

    /**
     * 验证UserIdentifyVO对象必输属性是否存在
     * @param userIdentifyVO
     * @throws BizException
     */
    private void verifyUserIdentifyVO(UserIdentifyVO userIdentifyVO) throws BizException {
        if(userIdentifyVO==null){
            logger.warn(userIdentifyVOMissing.getMessage(),userIdentifyVOMissing);
            throw userIdentifyVOMissing;
        }
        //判断必输值是否都输入
        if(userIdentifyVO.getRealName()==null||"".equals(userIdentifyVO.getRealName())||
            userIdentifyVO.getCardType()==null||
            userIdentifyVO.getCardNo()==null||"".equals(userIdentifyVO.getCardNo())||
            userIdentifyVO.getPhone()==null||"".equals(userIdentifyVO.getPhone())){
            logger.warn(userIdentifyVOFieldMissing.getMessage(),userIdentifyVOFieldMissing);
            throw userIdentifyVOFieldMissing;
        }
    }
    
    @Override
    public String registerThirdUser(UserInfoVO userInfoVO, UserThirdLoginVO userThirdLoginVO, UserIdentifyVO userIdentify) throws BizException {
        //验证userThirdLoginVO对象必输属性是否存在
        verifyUserThirdLoginVO(userThirdLoginVO);
        
        //判断第三方登录账号已否已存在
        if(queryThirdUser(userThirdLoginVO.getPartnerId(),userThirdLoginVO.getThirdloginType(),userThirdLoginVO.getThirduserId())!=null){            
            logger.warn(LogFormatTemplate.USER_THIRD_AUTH_SERVICE_REGISTER_THIRD_USER_WARN, new String[] { "coupon", userThirdLoginVO.getPartnerId(),
                    String.valueOf(userThirdLoginVO.getThirdloginType()), userThirdLoginVO.getThirduserId(), userThirdExist.getMessage() });

            logger.warn(userThirdExist.getMessage(),userThirdExist);
            throw userThirdExist;            
        }        
        
        //验证UserIdentifyVO对象必输属性是否存在
        verifyUserIdentifyVO(userIdentify);
 
        String userId=proxySelf.registerThirdUserTransaction(  userInfoVO,   userThirdLoginVO,   userIdentify);
        
        log(LogFormatTemplate.USER_THIRD_AUTH_SERVICE_REGISTER_THIRD_USER,new String[]{"user",userId,userInfoVO.getPartnerId()});

        return userId;
    }
  
    
    
    @MyTransactional
    public String registerThirdUserTransaction(UserInfoVO userInfoVO, UserThirdLoginVO userThirdLoginVO, UserIdentifyVO userIdentify) throws BizException{
        
        String userId=this.registerThirdUserCommon(userInfoVO, userThirdLoginVO);
        userIdentifyService.realName(userId, userIdentify);
        return userId;
        
    }
    
    @Override
    public int bindThirdUser(String userId, UserThirdLoginVO userThirdLoginVO) throws BizException{

        if(userId==null){
            logger.warn(userIdMissing.getMessage(),userIdMissing);
            throw userIdMissing;
        }

        //验证userThirdLoginVO对象必输属性是否存在
        verifyUserThirdLoginVO(userThirdLoginVO);
        
        log(LogFormatTemplate.USER_THIRD_AUTH_SERVICE_BIND_THIRD_USER,new String[]{"user",userId,userThirdLoginVO.getThirduserId() });
        
        int result=proxySelf.bindThirdUserTransaction(userId,userThirdLoginVO);

        return result;
    }

    /**
     * 注册第三方登录账号
     * @param userId
     * @param userThirdLoginVO
     * @throws BizException
     */
    private int registerThirdLogin(String userId, UserThirdLoginVO userThirdLoginVO) throws BizException {

        //注册第三方帐号
        userThirdLoginVO.setUserId(userId);

        //将VO对象转换成数据库映射对象
        UserThirdLogin userThirdLogin;

        userThirdLogin = (UserThirdLogin) ObjectOperation.convertByClasses(userThirdLoginVO, UserThirdLogin.class);

        return userThirdLoginDao.insert(userThirdLogin);
    }
    @MyTransactional
    public int bindThirdUserTransaction(String userId, UserThirdLoginVO userThirdLoginVO) throws BizException{
        return registerThirdLogin(userId, userThirdLoginVO);
    }
    @Override
    public UserInfoVO thirdUserLogin(String partnerId, int thirdLoginType, String thirdUserId) throws BizException {
        log(LogFormatTemplate.USER_THIRD_AUTH_SERVICE_THIRD_USER_LOGIN,new String[]{"user",partnerId,thirdUserId});
   
        //判断必输值是否都输入
        if(partnerId==null||"".equals(partnerId)){          
            logger.warn(partnerIdMissing.getMessage(),partnerIdMissing);
            throw partnerIdMissing;
        }
        
        
        //判断第三方登录账号类型是否支持
        if(thirdLoginType!= UserConst.UserThirdLoginType.WEIXIN.getCode() &&
                thirdLoginType!= UserConst.UserThirdLoginType.QQ.getCode()){
            logger.warn(userThirdTypeNotExist.getMessage(),userThirdTypeNotExist);
            throw userThirdTypeNotExist;
        }
 
        //判断必输值是否都输入
        if(thirdUserId==null||"".equals(thirdUserId)){
            logger.warn(userThirdIdMissing.getMessage(),userThirdIdMissing);
            throw userThirdIdMissing;
        }
        
 
        //查询第三方帐号类型、账号查询用户信息
        UserInfo userInfo=this.queryThirdUser(partnerId, thirdLoginType, thirdUserId);
        
        if(userInfo==null){
            //抛出不存在异常
            logger.warn(userThirdNotExist.getMessage(),userThirdNotExist);
            throw userThirdNotExist;
        }           
        //用户是否注销
        if(userInfo.getStatus()== UserConst.UserStatus.LOGOFFSTATUS.getCode()){
            //抛出用户已注销异常
            logger.warn(userStatusIsLogoff.getMessage(),userStatusIsLogoff);
            throw userStatusIsLogoff;
        }
        UserInfoVO userInfoVo = null;

        userInfoVo = (UserInfoVO) ObjectOperation.convertByClasses(userInfo, UserInfoVO.class);

        return userInfoVo;
        

    }
    
    private void log(String template, String[] content){
        logger.info(template,content);
        
    }
 
 
}
